package com.boot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

@Controller
public class UserController {

    @Autowired
    private SessionDAO sessionDAO;

    @RequestMapping("/{url}")
    public String login(@PathVariable("url")String url){
        return url;
    }

    @RequestMapping("/login_finish")
    public String login_finish(String username, String password,String rememberme, HttpServletRequest request){
        Subject currentUser = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            Collection<Session> sessions = sessionDAO.getActiveSessions();

            for(Session session:sessions){
                if(username!=null && username.equals(String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)))) {
                    session.setTimeout(0);//设置session立即失效，即将其踢出系统
                    request.setAttribute("msg","已经在其他地方登陆");
                    return "error";
                }
            }

            currentUser.login(token);
            Session session = currentUser.getSession();
            session.setAttribute("mySession",username+":MySession");
        } catch (Exception e) {
            System.out.println("登陆异常："+e.getMessage());
            request.setAttribute("msg","账号密码错误");
            return "error";
        }

        return "redirect:/success";
    }

    @RequestMapping("/success")
    public String success(){
        return "success";
    }

    @RequestMapping("/unauthorized")
    public String unauthorized(){
        return "unauthorized";
    }

    @GetMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }

}
